package yxy.game.pm2.command.player;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.Sign;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlayerMessage;

/** 玩家 修改头像框 */
@MessageType(proto = Command.PlayerHeadFrameChange, classtype = PlayerMessage.PlayerHeadFrameChangeRequest.class)
public class CMD_PlayerHeadFrameChange extends Command<PlayerMessage.PlayerHeadFrameChangeRequest> {

	@Override
	public void execute(MessageSource messageSource, PlayerMessage.PlayerHeadFrameChangeRequest request) {
		String playerCode = messageSource.getTag();
		int headframe = request.getHeadFrame();

		PlayerMessage.PlayerHeadFrameChangeResponse.Builder response = PlayerMessage.PlayerHeadFrameChangeResponse.newBuilder();

		if (headframe > 0 && !Sign.exist(playerCode, CurrencyType.CT_头像框, headframe)) {
			send(messageSource, response, Result.PlayerHeadframeNotGet);
			return;
		}
		PlayerBean playerBean = PlayerBean.get(playerCode);
		try {
			if (playerBean.tryLock()) {
				playerBean.setHeadframe(headframe);
				playerBean.set();

				response.setHeadFrame(playerBean.getHeadframe());
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			playerBean.unlock();
		}
	}

	private void send(MessageSource messageSource, PlayerMessage.PlayerHeadFrameChangeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}